<template>
    <div class="filter">
        <div class="filter-item">
            <label for="">所属单位：</label>
            <el-select
                v-model="searchForm.depId"
                class="m-2"
                style="width: 145px"
                :disabled="localTypeUnit != '1'"
            >
                <el-option
                    v-for="item in depIdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>

        <div class="filter-item">
            <label for="">值班日期：</label>
            <el-date-picker
                style="width: 145px"
                v-model="searchForm.taskDate"
                format="YYYY-MM-DD"
                type="date"
                :size="'default'"
            />
        </div>
        <div class="filter-item">
            <label for="">值班人数：</label>
            <el-input
                v-model="searchForm.onDutyCount"
                style="width: 145px"
                disabled
            />
        </div>
        <div class="filter-item">
            <label for="">值班人员：</label>
            <el-input
                v-model="searchForm.onDutyName"
                style="width: 180px"
                disabled
            />
        </div>
        <div class="filter-item">
            <el-button
                size="default"
                type="primary"
                @click="chooceTodayTask"
                :disabled="hasMember"
            >选择今日任务</el-button>
        </div>
    </div>

    <el-tabs
        v-model="tableActiveName"
        class="demo-tabs"
    >
        <el-tab-pane
            label="我的任务"
            name="my"
        >
            <el-table
                :data="myTask"
                style="width: 100%"
                id="inspectionTask"
                v-if="myTask.length > 0"
            >
                <el-table-column
                    prop="time"
                    label="推荐时间"
                    width="100"
                >
                    <template #default="scope">
                        <span
                            :class="timeTipClass(scope.row, scope.$index)"
                            v-if="scope.row.planStartTime"
                        >{{scope.row.planStartTime}}-{{scope.row.planEndTime}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="title"
                    label="任务项"
                    width="100"
                />
                <el-table-column
                    prop="stepTitle"
                    label="操作步骤"
                    width="150"
                />
                <el-table-column
                    prop="decomposeStepTitle"
                    label="步骤分解"
                    width="150"
                />
                <el-table-column
                    prop="finishCheck"
                    label=""
                    width="46"
                >
                    <template #default="scope">
                        <el-checkbox
                            v-model="myTaskReportContent[scope.$index]"
                            @change="finishCheckChange"
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="content"
                    label="具体内容"
                >
                    <template #default="scope">
                        <div style="display: flex;flex-direction: row;align-items: center;">
                            <el-tooltip
                                class="box-item"
                                effect="dark"
                                placement="top"
                            >
                                <template #content>
                                    <div style="max-width: 500px;">{{scope.row.content}}</div>
                                </template>
                                <div class="contentStyle">{{ scope.row.content }}</div>
                            </el-tooltip>
                            <el-tooltip
                                class="box-item"
                                effect="light"
                                placement="top"
                                v-if="scope.row.considerations"
                            >
                                <template #content>
                                    <div style="max-width: 500px;">{{scope.row.considerations}}</div>
                                </template>
                                <el-icon
                                    color="#58be3f"
                                    size="18"
                                    style="margin-left: 5px;"
                                >
                                    <QuestionFilled />
                                </el-icon>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="checkResult"
                    label="检测结果"
                    width="80"
                >
                    <template #default="scope">
                        <div class="loactionResult">
                            <div class="loactionResultEdit">
                                <el-button
                                    type="primary"
                                    size="small"
                                    :icon="Edit"
                                    @click="handleClick('edit', scope.row)"
                                    style="margin-right: 4px;"
                                >
                                </el-button>
                            </div>
                            <!-- <div
                                class="loactionResultEdit"
                                v-if="scope.row.id == 3280 || scope.row.id == 3283 || scope.row.id == 3286"
                            >
                                <el-button
                                    type="primary"
                                    size="small"
                                    :icon="Histogram"
                                    @click="handleClick('edit', scope.row)"
                                >
                                </el-button>
                            </div> -->
                        </div>

                    </template>
                </el-table-column>
            </el-table>
            <el-empty
                v-else
                description="暂无任务"
            />
        </el-tab-pane>
        <el-tab-pane
            label="全部任务"
            name="all"
        >
            <el-empty description="暂无任务" />
        </el-tab-pane>
    </el-tabs>

    <el-dialog
        v-model="chooceTaskVisiable"
        title="选择今日任务"
        width="900"
    >
        <div style="padding: 0 10px;">
            <div class="taskInfo">
                <p>值班日期： {{ moment(searchForm.taskDate).format('YYYY-MM-DD')}}</p>
                <p>值班人数： {{ searchForm.onDutyCount }}</p>
                <p>值班人员： {{ searchForm.onDutyName }}</p>
            </div>

            <el-tabs
                v-model="dialogActiveName"
                class="demo-tabs"
            >
                <el-tab-pane
                    :label="item.templateName"
                    :name="index"
                    v-for="(item, index) in templateList.list"
                    :key="index"
                >
                    <div class="templateInfo">
                        <div
                            class="templateInfoItem"
                            v-for="m in item.personnelNum"
                            :key="m"
                        >
                            <div class="templateInfoItemHeader">
                                <div class="itemTitle">任务项</div>
                                <div class="itemChecked">
                                    <el-checkbox
                                        v-if="m == 1"
                                        v-model="item.templatechecked1"
                                        @change="(val) => templatechecked(val, index, m)"
                                    />
                                    <el-checkbox
                                        v-if="m == 2"
                                        v-model="item.templatechecked2"
                                        @change="(val) => templatechecked(val, index, m)"
                                    />
                                    <el-checkbox
                                        v-if="m == 3"
                                        v-model="item.templatechecked3"
                                        @change="(val) => templatechecked(val, index, m)"
                                    />
                                </div>
                            </div>
                            <div
                                class="templateInfoItemContent"
                                v-if="m == 1"
                            >
                                <p
                                    v-for="p in item.requiredTitlesItemsList"
                                    :key="p"
                                >
                                    {{ p}}
                                </p>
                            </div>
                            <div
                                class="templateInfoItemContent"
                                v-if="m == 2"
                            >
                                <p
                                    v-for="p in item.requiredTitlesItemsList"
                                    :key="p"
                                >
                                    {{ p }}
                                </p>
                            </div>
                            <div
                                class="templateInfoItemContent"
                                v-if="m == 3"
                            >
                                <p
                                    v-for="p in item.requiredTitlesItemsList"
                                    :key="p"
                                >
                                    {{ p }}
                                </p>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane
                    label="自定义"
                    name="custom"
                >
                    <div class="templateInfo">
                        <div class="templateInfoItem all">
                            <p
                                v-for="item in taskList"
                                :key="item.id"
                            >
                                <el-checkbox-group v-model="checkList">
                                    <el-checkbox :value="item.id">{{ item.title }}</el-checkbox>
                                </el-checkbox-group>
                            </p>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="chooceTaskVisiable = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="chooceTaskConfirm()"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog
        v-model="configVisible"
        :title="configTitle"
        width="792"
    >
        <div class="dialogContent">
            <el-form
                ref="configFormRef"
                :model="configForm"
                label-width="82px"
                class="demo-ruleForm"
                :inline="true"
            >
                <el-tabs
                    v-model="relatedIndicatorActiveName"
                    class="demo-tabs"
                    @tab-change="relatedIndicatorchange"
                >
                    <el-tab-pane
                        v-for="(item, index) in configForm.relatedIndicatorList"
                        :key="index"
                        :label="item.indicatorName"
                        :name="index"
                    >
                        <el-scrollbar height="460px">
                            <div class="dialogModel">
                                <el-row>
                                    <el-col :span="7">
                                        <el-form-item
                                            label="仪器"
                                            prop="title"
                                            style="width: 100%;"
                                        >
                                            <el-input
                                                v-model="item.instrument"
                                                placeholder="请输入"
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="7">
                                        <el-form-item
                                            label="方法"
                                            prop="title"
                                            style="width: 100%;"
                                        >
                                            <el-input
                                                v-model="item.methodName"
                                                placeholder="请输入"
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="7">
                                        <el-form-item
                                            label="环境"
                                            prop="title"
                                            style="width: 100%;"
                                        >
                                            <el-input
                                                v-model="item.environment"
                                                placeholder="请输入"
                                            />
                                        </el-form-item>
                                    </el-col>

                                </el-row>
                            </div>
                            <div class="dialogModel">
                                <div class="modelTitle">
                                    <div>计算公式</div>
                                </div>
                                <el-tabs
                                    v-model="formulaMainListActiveName"
                                    class="demo-tabs"
                                >
                                    <el-tab-pane
                                        v-for="(m, n) in configForm.formulaMainList"
                                        :key="n"
                                        :label="m.formulaName"
                                        :name="n"
                                    >
                                        <el-row v-if="m.description">
                                            <el-col :span="24">
                                                <el-form-item
                                                    label="说明:"
                                                    prop="expression"
                                                    style="width: 100%;"
                                                >
                                                    <p>{{ m.description }}</p>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-for="(p, q) in m.inputValuesList"
                                            :key="q"
                                            v-show="relatedIndicatorActiveCode == p.currentActiveName"
                                        >
                                            <el-col :span="3">
                                                <el-form-item
                                                    label=""
                                                    prop="description"
                                                    style="width: 100%;"
                                                >
                                                    <p
                                                        v-if="!p.temporary"
                                                        style="width: 100%; text-align: right;"
                                                    >{{ p.dailyIndicator }}</p>

                                                    <el-input
                                                        v-else
                                                        v-model="p.dailyIndicator"
                                                        placeholder="样品来源"
                                                    />
                                                </el-form-item>
                                            </el-col>
                                            <el-col
                                                :span="2"
                                                v-for="(j,k) in m.processValuePos"
                                                :key="k"
                                            >
                                                <div
                                                    class="el-col-content"
                                                    style="margin-left: 10px;"
                                                >
                                                    <el-input
                                                        v-model="p[j.valueName]"
                                                        :placeholder="j.valueName"
                                                        :disabled="j.valueName == 'a' || j.valueName == 'b'"
                                                    />
                                                </div>
                                            </el-col>
                                            <el-col
                                                :span="2"
                                                v-if="p.temporary"
                                            >
                                                <div
                                                    class="el-col-content el-col-content-mr"
                                                    @click="deleteTemporaryInspection(index, q)"
                                                    style="margin: 6px 0 0 6px"
                                                >
                                                    <img
                                                        src="../../../../assets/images/minus.png"
                                                        alt=""
                                                        style=" width: 20px;height: 20px;margin-right: 4px;"
                                                    >
                                                </div>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="24">
                                                <el-form-item
                                                    label=" "
                                                    prop="description"
                                                    style="width: 100%;"
                                                >
                                                    <div
                                                        class="el-col-content el-col-content-mr"
                                                        @click="addTemporaryInspection(n)"
                                                    >
                                                        <img
                                                            src="../../../../assets/images/plus.png"
                                                            alt=""
                                                            style=" width: 20px;height: 20px;margin-right: 4px;"
                                                        >
                                                        <span>临时检测</span>
                                                    </div>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="24">
                                                <el-form-item
                                                    label=" "
                                                    prop="expression"
                                                    style="width: 100%;"
                                                >

                                                    <el-checkbox v-model="m.checked1">{{ m.expression }}</el-checkbox>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row v-if="m.taskId == 3280 || m.taskId == 3283 || m.taskId == 3286">
                                            <el-col :span="10">
                                                <el-form-item
                                                    label=" "
                                                    prop="expression"
                                                    style="width: 100%;"
                                                >
                                                    <div class="curveEquation">
                                                        <el-checkbox
                                                            v-model="m.checked2"
                                                            @change="(val) => checkedChange(val, 2)"
                                                        >曲线方程</el-checkbox>
                                                        <el-select
                                                            v-model="m.lineId"
                                                            class="m-2"
                                                            style="width: 200px;margin-left: 20px;"
                                                            :disabled="localTypeUnit != '1'"
                                                            @change="(val) => linearEquationChange(val, n)"
                                                        >
                                                            <el-option
                                                                v-for="p in linearEquationList"
                                                                :key="p.id"
                                                                :label="p.lineName"
                                                                :value="p.id"
                                                            />
                                                        </el-select>
                                                    </div>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="8">
                                                <el-form-item
                                                    label=" "
                                                    prop="expression"
                                                    style="width: 100%;"
                                                >
                                                    <div
                                                        class="curveEquation"
                                                        v-show="m.checked2"
                                                    >
                                                        {{ m.lineExpression }}
                                                    </div>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <!-- <el-row>
                                            <el-col :span="24">
                                                <el-form-item
                                                    label=" "
                                                    prop="description"
                                                    style="width: 100%;"
                                                >
                                                    <el-checkbox
                                                        style="width: 96px;"
                                                        v-model="checked3"
                                                        @change="(val) => checkedChange(val, 3)"
                                                    >自定义</el-checkbox>
                                                    <div
                                                        class="el-col-content el-col-content-mr"
                                                        @click="addFormulaProcessValue(index)"
                                                    >
                                                        <img
                                                            src="../../../../assets/images/plus.png"
                                                            alt=""
                                                            style=" width: 20px;height: 20px;margin-right: 4px;"
                                                        >
                                                        <span>过程值</span>
                                                    </div>
                                                    <div
                                                        class="el-col-content el-col-content-mr"
                                                        @click="addFormulaNumber(index)"
                                                    >
                                                        <img
                                                            src="../../../../assets/images/plus.png"
                                                            alt=""
                                                            style=" width: 20px;height: 20px;margin-right: 4px;"
                                                        >
                                                        <span>数字</span>
                                                    </div>
                                                    <div
                                                        class="el-col-content el-col-content-mr"
                                                        @click="addFormulaOperator(index)"
                                                    >
                                                        <img
                                                            src="../../../../assets/images/plus.png"
                                                            alt=""
                                                            style=" width: 20px;height: 20px;margin-right: 4px;"
                                                        >
                                                        <span>运算符号</span>
                                                    </div>
                                                    <div
                                                        class="el-col-content el-col-content-mr"
                                                        @click="clearFormula(n)"
                                                    >
                                                        <img
                                                            src="../../../../assets/images/minus.png"
                                                            alt=""
                                                            style=" width: 20px;height: 20px;margin-right: 4px;"
                                                        >
                                                        <span>清空</span>
                                                    </div>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <div
                                            class="calculationFormula"
                                            v-if="m.temporaryCalculationFormulaContent.length > 0"
                                        >
                                            <div style="width: 82px;"></div>
                                            <div class="calculationFormulaContent">
                                                <p>公式</p>
                                                <div>
                                                    <span
                                                        v-for="k in m.temporaryCalculationFormulaContent"
                                                        :key="k"
                                                        style="margin-right: 10px;"
                                                    >{{ k.value }}</span>
                                                </div>
                                            </div>

                                        </div>
                                        <div class="calculationFormula">
                                            <div style="width: 82px;"></div>
                                            <div class="calculationFormulaContent">
                                                <div
                                                    style="padding: 3px 6px 3px 0px"
                                                    v-for="(t, x) in m.temporaryCalculationFormulaContent"
                                                    :key="x"
                                                    class="calculationFormulaContentItem"
                                                >
                                                    <div
                                                        class="delelteItem"
                                                        @click="delelteCalculationFormulaItem(n,x)"
                                                    >
                                                        <el-icon
                                                            class="elIcon"
                                                            :size="12"
                                                            color="#fff"
                                                        >
                                                            <Delete />
                                                        </el-icon>
                                                    </div>
                                                    <el-select
                                                        v-if="t.type == '1'"
                                                        v-model="t.value"
                                                        class="m-2"
                                                        style="width: 100px"
                                                        placeholder="过程值"
                                                    >
                                                        <el-option
                                                            v-for="j in m.processValuePos"
                                                            :key="j.valueName"
                                                            :label="j.valueName"
                                                            :value="j.valueName"
                                                        />
                                                    </el-select>
                                                    <el-input-number
                                                        controls-position="right"
                                                        v-if="t.type == '2'"
                                                        v-model="t.value"
                                                        style="width: 100px"
                                                        placeholder="数值"
                                                    />
                                                    <el-select
                                                        v-if="t.type == '3'"
                                                        v-model="t.value"
                                                        class="m-2"
                                                        style="width: 100px"
                                                        placeholder="运算符号"
                                                    >
                                                        <el-option
                                                            v-for="j in operatorList"
                                                            :key="j"
                                                            :label="j"
                                                            :value="j"
                                                        />
                                                    </el-select>
                                                </div>
                                            </div>
                                        </div> -->
                                    </el-tab-pane>
                                </el-tabs>
                            </div>
                            <div class="dialogModel">
                                <div
                                    class="modelTitle"
                                    style="margin-bottom: 20px;"
                                >
                                    <div>结果值(合规范围: 6-9)</div>
                                    <div class="operateIcon">
                                        <el-button
                                            type="primary"
                                            size="small"
                                            @click="formulaResultvalue(index)"
                                        >
                                            计算
                                        </el-button>
                                    </div>
                                </div>
                                <div v-if="configForm.formulaMainList && configForm.formulaMainList.length > 0">
                                    <div
                                        v-for="(p, q) in configForm.formulaMainList[relatedIndicatorActiveName].inputValuesList"
                                        :key="q"
                                        v-show="relatedIndicatorActiveCode == p.currentActiveName"
                                    >
                                        <el-form-item
                                            :label="p.dailyIndicator"
                                            prop="expression"
                                        >
                                            <el-input
                                                style="width: 145px;"
                                                v-model="p.result"
                                            ></el-input>
                                        </el-form-item>
                                    </div>
                                </div>
                            </div>
                        </el-scrollbar>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="configVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="resultValueConfirm()"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
// utils
import Storage from "@/utils/storage.js";
import {
    Edit,
    QuestionFilled
} from "@element-plus/icons-vue";
import moment from 'moment';
import { onMounted, reactive, ref, watch } from "vue";
// api
import schedulingHttp from "@/https/scheduling.js";
import taskHttp from "@/https/task.js";
import { ElMessage } from "element-plus";

// ref
let searchForm = ref({
    depId: Storage.localGet("depId"),
    // taskDate: moment().add(-1, 'day').format('YYYY-MM-DD'),
    taskDate: '2025-03-16',
    onDutyCount: '',
    onDutyName: '',
    taskTemplateId: '',
});
const localTypeUnit = ref();
localTypeUnit.value = Storage.localGet("depId")
searchForm.value.depId = localTypeUnit.value == '1' ? '2' : Number(localTypeUnit.value)
searchForm.value.depId = '5'
const chooceTaskVisiable = ref(false);
const checkList = ref([]);
const tableActiveName = ref('my');
const dialogActiveName = ref(0);
// dict
const depIdList = ref([
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const itemList = ref([
    { label: "pH", value: "pH" },
    { label: "SS", value: "SS" },
    { label: "COD", value: "COD" },
    { label: "BOD5", value: "BOD5" },
    { label: "TN", value: "TN" },
]);
const itemList2 = ref([
    { label: "pH", value: "pH" },
    { label: "SS", value: "SS" },
    { label: "COD", value: "COD" },
    { label: "BOD5", value: "BOD5" },
    { label: "TN、TP、NH3-N", value: "TN、TP、NH3-N" },
    { label: "粪大肠菌群", value: "粪大肠菌群" },
    { label: "色度", value: "色度" },
    { label: "DO", value: "DO" },
    { label: "MLSS", value: "MLSS" },
    { label: "SV30", value: "SV30" },
    { label: "SV30", value: "SV30" },
    { label: "MLVSS", value: "MLVSS" },
    { label: "污泥含水率", value: "污泥含水率" },
]);
const labTeamId = (depId) => {
    let teamId = '1'
    if (depId == 2) {
        teamId = '1'
    } else if (depId == 3) {
        teamId = '1'
    } else if (depId == 4) {
        teamId = '1'
    } else if (depId == 5) {
        teamId = '41'
    } else if (depId == 6) {
        teamId = '1'
    }
    return teamId
}
const hasMember = ref(false)
const memberList = ref([])
const linearEquationList = ref([])

// methods
const getTaskMemberList = async () => {
    let teamId = labTeamId(searchForm.value.depId)
    let params = {
        depId: searchForm.value.depId,
        startTime: moment(searchForm.value.taskDate).format('YYYY-MM-DD'),
        endTime: moment(searchForm.value.taskDate).format('YYYY-MM-DD'),
        teamId: labTeamId(searchForm.value.depId),
        userRealName: null,
        classId: null,
        pageNo: 1,
        pageSize: 10,
    }
    const res = await schedulingHttp.workPlanQueryUserWorkPlanPage(params)
    if (res.data.data.records.length > 0) {
        let onDutyNameList = []
        let onDutyIdList = []
        res.data.data.records.forEach(item => {
            onDutyNameList.push(item.realName)
            onDutyIdList.push(item.userId)
        })
        searchForm.value.onDutyCount = res.data.data.records.length
        searchForm.value.onDutyName = onDutyNameList.join('、')
        memberList.value = onDutyIdList

        if (memberList.value.includes(Storage.localGet("userId"))) {
            hasMember.value = true
        } else {
            hasMember.value = false
        }
    } else {
        searchForm.value.onDutyCount = ''
        searchForm.value.onDutyName = ''
        hasMember.value = false
    }
    reportConfigsearch()
}
let templateList = reactive({
    list: []
})
// 查询
const templateListFn = async () => {
    const res = await taskHttp.queryTaskTemplateList(searchForm.value)
    let list = res.data.data.personn1List.concat(res.data.data.personn2List.concat(res.data.data.personn3List))
    list.forEach(item => {
        item.requiredTitlesItemsList = item.requiredTitlesItems ? item.requiredTitlesItems.split(',') : []
        item.requiredTitlesItems2List = item.requiredTitlesItems2 ? item.requiredTitlesItems2.split(',') : []
        item.requiredTitlesItems3List = item.requiredTitlesItems3 ? item.requiredTitlesItems3.split(',') : []
        item.templateChecked1 = false
        item.templateChecked2 = false
        item.templateChecked3 = false
    })
    templateList.list = list

}
// 选中清空其他
const templatechecked = (val, index, m) => {
    checkList.value = []
    if (val) {
        templateList.list.forEach(item => {
            item[`templatechecked1`] = false
            item[`templatechecked2`] = false
            item[`templatechecked3`] = false
        })
        templateList.list[index][`templatechecked${m}`] = true
        // checkList.value = []
    }
}
const taskList = ref([])
// 查询
const taskListFn = async () => {
    const res = await taskHttp.queryTaskList(searchForm.value)
    taskList.value = res.data.data
}
const taskListIdToName = async (taskIds) => {
    let taskName = []
    let taskIdsList = taskIds.split(',')
    taskIdsList.forEach(item => {
        taskList.value.forEach(m => {
            if (item == m.id) {
                taskName.push(m.title)
            }
        })
    })
    return taskName.join(',')
}
// 选择今日任务
const chooceTodayTask = async () => {
    chooceTaskVisiable.value = true
}
// 确认今日任务
const chooceTaskConfirm = async () => {
    let params = {
        depId: searchForm.value.depId,
        requiredIdsItems: '',
        requiredTitlesItems: '',
        taskDate: moment(searchForm.value.taskDate).format('YYYY-MM-DD'),
        userId: '',
        taskTemplateId: '',
    }
    if (checkList.value.length > 0) { // 选了自定义
        params.requiredIdsItems = checkList.value.join(',')
        params.requiredTitlesItems = taskListIdToName(params.requiredIdsItems)
    } else {
        templateList.list.forEach(item => {
            if (item[`templatechecked1`]) {
                params.requiredIdsItems = item.requiredIdsItems
                params.requiredTitlesItems = item.requiredTitlesItems
                params.taskTemplateId = item.id
            }
            if (item[`templatechecked2`]) {
                params.requiredIdsItems = item.requiredIdsItems2
                params.requiredTitlesItems = item.requiredTitlesItems2
                params.taskTemplateId = item.id
            }
            if (item[`templatechecked3`]) {
                params.requiredIdsItems = item.requiredIdsItems3
                params.requiredTitlesItems = item.requiredTitlesItems3
                params.taskTemplateId = item.id
            }
        })
    }
    if (myTask.value.length > 0) {
        const res = await taskHttp.updateUserLabtask(params)
    } else {
        const res = await taskHttp.addUserLabtask(params)
    }
    chooceTaskVisiable.value = false
    search()
}
const allTask = ref([])
const myTask = ref([])
const myTaskObj = ref([])
const allTaskObj = ref([])
const myTaskReportContent = ref([])
const allTaskReportContent = ref([])
// 查询
const search = async () => {
    allTask.value = []
    myTask.value = []
    // 全部任务
    let params = {
        depId: searchForm.value.depId,
        taskDate: moment(searchForm.value.taskDate).format('YYYY-MM-DD')
    }
    const res = await taskHttp.queryUserLabtaskBydate(params)
    let allList = []
    if (res.data.data.id) {
        allTaskObj.value = res.data.data
        let allTaskTemplateTimesetVos = JSON.parse(res.data.data.taskTemplatePo.taskTemplateTimesetVos)
        res.data.data.taskVoList && res.data.data.taskVoList.forEach(item => {
            if (item.childrens && item.childrens.length > 0) {
                item.childrens.forEach(m => {
                    if (m.childrens && m.childrens.length > 0) {
                        m.childrens.forEach(p => {
                            allList.push({
                                taskId: item.id,
                                id: item.id,
                                title: item.title,
                                stepId: m.id,
                                stepTitle: m.title,
                                decomposeStepId: p.id,
                                decomposeStepTitle: p.title,
                                time: '',
                                content: p.description,
                                complianceScope: '',
                                location: p.location,
                                checkResult: '',
                                considerations: p.considerations,
                            })
                        })
                    } else {
                        allList.push({
                            taskId: item.id,
                            id: item.id,
                            title: item.title,
                            stepId: m.id,
                            stepTitle: m.title,
                            decomposeStepId: '',
                            decomposeStepTitle: '',
                            time: '',
                            content: '',
                            complianceScope: '',
                            location: '',
                            checkResult: '',
                        })
                    }
                })
            } else {
                allList.push({
                    taskId: item.id,
                    id: item.id,
                    title: item.title,
                    stepId: '',
                    stepTitle: '',
                    decomposeStepId: '',
                    decomposeStepTitle: '',
                    time: '',
                    content: '',
                    complianceScope: '',
                    location: '',
                    checkResult: '',
                })
            }
        })
        allList.forEach((item, index) => {
            item.planStartTime = allTaskTemplateTimesetVos[index].planStartTime
            item.planEndTime = allTaskTemplateTimesetVos[index].planEndTime
        })
        if (allTaskObj.value.reportContent == null) {
            allTaskObj.value.reportContent = []
            myList.forEach((item, index) => {
                allTaskObj.value.reportContent.push(false)
            })
        }
    }
    allTask.value = allList

    // 我的任务
    let params2 = {
        depId: searchForm.value.depId,
        taskDate: moment(searchForm.value.taskDate).format('YYYY-MM-DD'),
        userId: Storage.localGet("userId")
    }
    const res2 = await taskHttp.queryUserLabtaskBydate(params2)
    let myList = []

    if (res2.data.data.id) {
        myTaskObj.value = res2.data.data
        let myTaskTemplateTimesetVos = JSON.parse(res2.data.data.taskTemplatePo.taskTemplateTimesetVos)
        res2.data.data.taskVoList && res2.data.data.taskVoList.forEach(item => {
            if (item.childrens && item.childrens.length > 0) {
                item.childrens.forEach(m => {
                    if (m.childrens && m.childrens.length > 0) {
                        m.childrens.forEach(p => {
                            myList.push({
                                taskId: item.id,
                                id: item.id,
                                title: item.title,
                                stepId: m.id,
                                stepTitle: m.title,
                                decomposeStepId: p.id,
                                decomposeStepTitle: p.title,
                                time: '',
                                content: p.description,
                                complianceScope: '',
                                location: p.location,
                                checkResult: '',
                                considerations: p.considerations,
                            })
                        })
                    } else {
                        myList.push({
                            taskId: item.id,
                            id: item.id,
                            title: item.title,
                            stepId: m.id,
                            stepTitle: m.title,
                            decomposeStepId: '',
                            decomposeStepTitle: '',
                            time: '',
                            content: '',
                            complianceScope: '',
                            location: '',
                            checkResult: '',
                        })
                    }
                })
            } else {
                myList.push({
                    taskId: item.id,
                    id: item.id,
                    title: item.title,
                    stepId: '',
                    stepTitle: '',
                    decomposeStepId: '',
                    decomposeStepTitle: '',
                    time: '',
                    content: '',
                    complianceScope: '',
                    location: '',
                    checkResult: '',
                })
            }
        })
        myList.forEach((item, index) => {
            item.planStartTime = myTaskTemplateTimesetVos[index].planStartTime
            item.planEndTime = myTaskTemplateTimesetVos[index].planEndTime
            taskToConfig(item)
        })
        myTaskReportContent.value = []
        if (myTaskObj.value.reportContent == null) {
            myTaskObj.value.reportContent = []
            myList.forEach((item, index) => {
                myTaskReportContent.value.push(false)
            })
        } else {
            myTaskReportContent.value = JSON.parse(myTaskObj.value.reportContent)
            // myTaskObj.value.reportContent = []
            // myList.forEach((item, index) => {
            //     myTaskReportContent.value.push(false)
            // })
        }
    }
    myTask.value = myList
    if (!res2.data.data.id) {
        chooceTaskVisiable.value = true
    }
}
const finishCheckChange = async () => {
    myTaskObj.value.reportContent = JSON.stringify(myTaskReportContent.value)
    myTaskObj.value.createTime = ''
    myTaskObj.value.updateTime = ''

    if (tableActiveName.value == 'my') {
        const res = await taskHttp.updateUserLabtask(myTaskObj.value)
    }
}
const reportConfigList = ref([])
const reportConfigTotal = ref([])
// 查询
const reportConfigsearch = async () => {
    const res = await taskHttp.reportPropertiesPageList(searchForm.value)
    res.data.data.records.forEach(item => {
        let arr = []
        let relationDailyItem = []
        item.relatedIndicatorList.forEach(m => {
            relationDailyItem.push(m.indicatorName)
            m.indicatorDetailList.forEach(p => {
                p.result = ''
                arr.push({
                    indicatorName: m.indicatorName,
                    ...p
                })
            })
        })
        item.relationDailyItemName = relationDailyItem.join('、')
        item.relatedIndicatorPlatList = arr
    })
    reportConfigList.value = res.data.data.records
    reportConfigTotal.value = res.data.data.total
    search()
}
const taskToConfig = (taskItem) => {
    reportConfigList.value.forEach(item => {
        if (taskItem.id == item.title) {
            taskItem.relatedIndicatorPlatList = item.relatedIndicatorPlatList
            taskItem.reportConfigId = item.id
        }
    })
}
const getTaskToConfigById = (id) => {
    let config = {}
    reportConfigList.value.forEach(item => {
        if (item.id == id) {
            config = item
        }
    })
    return config
}
const configVisible = ref(false)
const configTitle = ref('')
const configForm = ref({

})
const configFormRef = ref({})
const relatedIndicatorActiveName = ref(0)
const relatedIndicatorActiveCode = ref('')
const relatedIndicatorchange = () => {
    relatedIndicatorActiveCode.value = configForm.value.relatedIndicatorList[relatedIndicatorActiveName.value].indicatorName
}

const formulaMainListActiveName = ref(0)
const operatorList = ref(['+', '-', '*', '/', '(', ')', '%'])
// 
const handleClick = async (type, row) => {
    configVisible.value = true
    configForm.value = getTaskToConfigById(row.reportConfigId)
    configForm.value.taskId = row.taskId
    configTitle.value = configForm.value.relationDailyItemName + '测试'
    console.log(configForm.value)

    const res = await taskHttp.queryTaskDetailById({ id: row.id })
    let taskData = res.data.data
    if (row.id == 3280 || row.id == 3283 || row.id == 3286) {
        let lineType = row.id == 3280 ? 2 : row.id == 3283 ? 1 : row.id == 3286 ? 3 : ''
        linearEquation(lineType)
    }
    renameChildren(taskData)
    taskData.formulaMainList.forEach(item => {
        if (item.calculationFormulaContent) {
            item.calculationFormulaContent = JSON.parse(item.calculationFormulaContent)
        } else {
            item.calculationFormulaContent = []
        }
        item.lineId = ''
        item.lineExpression = ''
        item.slope = ''
        item.rsquared = ''
        item.intercept = ''
        item.lineName = ''
        item.lineCategory = ''
        item.checked1 = true
        item.checked2 = false
        item.inputValuesList = []
        configForm.value.relatedIndicatorList.forEach(m => {
            m.instrument = ''
            m.methodName = ''
            m.environment = ''
            m.indicatorDetailList.forEach(p => {
                let inputValuesListItem = {
                    currentActiveName: m.indicatorName,
                    indicatorName: m.indicatorName,
                    dailyIndicator: p.dailyIndicator,
                    relatedIndicator: p.relatedIndicator,
                    formulaId: item.id,
                    inputValues: [],
                    inputValuesKey: [],
                    temporary: false,
                    result: '',
                }
                item.processValuePos.forEach(k => {
                    inputValuesListItem[k.valueName] = ''
                    inputValuesListItem.inputValues.push(k.meaning)
                    inputValuesListItem.inputValuesKey.push(k.valueName)
                })
                item.inputValuesList.push(inputValuesListItem)
            })
        })
        item.processValuePos.forEach(m => {
            m.value = ''
            m.temporary = false
        })
        item.temporaryCalculationFormulaContent = []
    })

    configForm.value.relatedIndicatorList.forEach(item => {
        item.formulaMainList = JSON.parse(JSON.stringify(taskData.formulaMainList))
        item.formulaMainListActiveName = 0
    })
    // configForm.value.formulaMainList = taskData.formulaMainList
    console.log(configForm.value, configForm.value.formulaMainList[relatedIndicatorActiveName.value], '111111')
    relatedIndicatorActiveCode.value = configForm.value.relatedIndicatorList[relatedIndicatorActiveName.value].indicatorName
}
// 递归字段名转换函数

function renameChildren (tree) {
    if (tree.hasOwnProperty('childrens')) {
        tree.childrenTasks = tree.childrens;
        delete tree.childrens;
    }
    if (tree.childrenTasks && Array.isArray(tree.childrenTasks)) {
        for (const child of tree.childrenTasks) {
            renameChildren(child);
        }
    }
}
// 增加临时检测
const addTemporaryInspection = (n) => {
    let org = configForm.value.formulaMainList[n]
    let inputValuesListItem = {
        currentActiveName: relatedIndicatorActiveCode.value,
        indicatorName: '',
        dailyIndicator: '',
        relatedIndicator: '',
        formulaId: '',
        inputValues: [],
        temporary: true,
        result: ''
    }
    org.processValuePos.forEach(k => {
        inputValuesListItem[k.valueName] = ''
        inputValuesListItem.inputValues.push(k.meaning)
    })
    if (org.lineId) {
        configForm.value.formulaMainList[n].inputValuesList.forEach(item => {
            inputValuesListItem.a = configForm.value.formulaMainList[n].slope
            inputValuesListItem.b = configForm.value.formulaMainList[n].intercept
        })
    }
    configForm.value.formulaMainList[n].inputValuesList.push(inputValuesListItem)
    console.log(configForm.value, '222222')
}
// 删除临时检测
const deleteTemporaryInspection = (index, q) => {
    console.log(index, q)
    configForm.value.formulaMainList[index].inputValuesList.splice(q, 1)
}
const checked1 = ref(true)
const checked2 = ref(false)
const checked3 = ref(false)
const checkedChange = (val, index) => {
    if (index == 2) {
        if (val) {

        }
    }
}
const linearEquationChange = (val, n) => {
    let linearEquationItem = {}
    linearEquationList.value.forEach(item => {
        if (item.id == val) {
            linearEquationItem = item
        }
    })
    configForm.value.formulaMainList[n].lineId = linearEquationItem.id
    configForm.value.formulaMainList[n].lineExpression = linearEquationItem.expression
    configForm.value.formulaMainList[n].slope = linearEquationItem.slope
    configForm.value.formulaMainList[n].rsquared = linearEquationItem.rsquared
    configForm.value.formulaMainList[n].intercept = linearEquationItem.intercept
    configForm.value.formulaMainList[n].lineName = linearEquationItem.lineName
    configForm.value.formulaMainList[n].lineCategory = linearEquationItem.lineCategory
    configForm.value.formulaMainList[n].inputValuesList.forEach(item => {
        item.a = linearEquationItem.slope
        item.b = linearEquationItem.intercept
    })
}
// 增加过程值
const addProcessValue = () => {
    configForm.value.formulaMainList[formulaMainListActiveName.value].processValuePos.push({
        valueName: '',
        meaning: '',
        unit: '',
        isBackup: false,
        backupDays: '',
    })
}
// 删除过程值
const deleteProcessValue = (item, index) => {
    configForm.value.formulaMainList[formulaMainListActiveName.value].processValuePos.splice(index, 1)
}
// 增加公式过程值
const addFormulaProcessValue = (index) => {
    configForm.value.formulaMainList[index].temporaryCalculationFormulaContent.push({
        type: '1',
        value: '',
    })
}
// 增加公式数值
const addFormulaNumber = (index) => {
    configForm.value.formulaMainList[index].temporaryCalculationFormulaContent.push({
        type: '2',
        value: '',
    })
}
// 增加公式运算符号
const addFormulaOperator = (index) => {
    configForm.value.formulaMainList[index].temporaryCalculationFormulaContent.push({
        type: '3',
        value: '',
    })
}
const delelteCalculationFormulaItem = (n, x) => {
    configForm.value.formulaMainList[n].temporaryCalculationFormulaContent.splice(x, 1)
}
// 清除公式
const clearFormula = (n) => {
    configForm.value.formulaMainList[n].temporaryCalculationFormulaContent = []
}
// 计算
const formulaResultvalue = async (m, n) => {
    if (configForm.value.formulaMainList[formulaMainListActiveName.value].checked1) {
        const trialBalQueue = configForm.value.formulaMainList[relatedIndicatorActiveName.value].inputValuesList.map(async (item, index) => {
            if (item.currentActiveName == relatedIndicatorActiveCode.value) {

                let inputValues = {}
                item.inputValuesKey.forEach(key => {
                    inputValues[key] = item[key]
                })
                let params = {
                    formulaId: item.formulaId,
                    taskid: configForm.value.taskId,
                    inputValues: inputValues
                }

                return await taskHttp.trialBal(params)
                console.log(res, 'trialBal')
            } else {
                return null
            }
        })
        const results = await Promise.all(trialBalQueue)
        results.forEach((item, index) => {
            if (item) {
                console.log(item)
                configForm.value.formulaMainList[relatedIndicatorActiveName.value].inputValuesList[index].result = item.data.data.data
            }
        })
    } else {
        ElMessage({
            type: 'warning',
            message: '请选择计算方式'
        })
    }
}

const resultValueConfirm = async () => {
    console.log(configForm.value, 'configForm.value.formulaMainList')
    // let params = []
    // let resultItem = {
    //     entryDate: searchForm.value.taskDate,
    //     environment: configForm.value.relatedIndicatorList[relatedIndicatorActiveName.value].environment,
    //     instrument: configForm.value.relatedIndicatorList[relatedIndicatorActiveName.value].instrument,
    //     methodName: configForm.value.relatedIndicatorList[relatedIndicatorActiveName.value].methodName,
    //     indicatorName: '',
    //     dailyIndicator: '',
    //     result: '',
    //     inputValues: '',
    //     relatedIndicatorActiveName: relatedIndicatorActiveName.value,
    //     formulaMainListActiveName: formulaMainListActiveName.value,
    // }
    // configForm.value.formulaMainList[relatedIndicatorActiveName.value].inputValuesList.forEach(item => {
    //     resultItem.indicatorName = item.indicatorName
    //     resultItem.dailyIndicator = item.x
    //     resultItem.result = item.result
    //     resultItem.inputValues = JSON.stringify(item)
    //     params.push(resultItem)
    // })
    // console.log(params, 'params')
    // const res = await taskHttp.labTaskReport(params)
    // console.log(res, 'res')
    // configVisible.value = false
}


const timeTipClass = (row, index) => {
    let className = ''
    let today = moment().format('YYYY-MM-DD')
    let todayTime = moment().format('YYYY-MM-DD HH:mm:ss')
    let start = moment(searchForm.value.taskDate).format('YYYY-MM-DD') + ` ${row.planStartTime}`
    let end = moment(searchForm.value.taskDate).format('YYYY-MM-DD') + ` ${row.planEndTime}`
    let currentPlanStartTime = moment(start).format('YYYY-MM-DD HH:mm:ss')
    let currentPlanEndTime = moment(end).format('YYYY-MM-DD HH:mm:ss')
    if (myTaskReportContent.value[index]) {
        className = 'success'
    } else if (moment(currentPlanEndTime).isBefore(moment(todayTime))) {
        className = 'danger'
    } else if (moment(todayTime).isBefore(moment(currentPlanEndTime)) && moment(currentPlanStartTime).isBefore(moment(todayTime))) {
        className = 'warning'
    } else if (moment(todayTime).isBefore(moment(currentPlanStartTime))) {
        className = 'nomarl'
    }
    return className
}

const linearEquation = async (type) => {
    let params = {
        lineCategory: type,
        // depId: searchForm.value.depId
    }
    const res = await taskHttp.queryLinearEquationList(params)
    linearEquationList.value = res.data.data
}
watch(
    () => searchForm.value,
    (val) => {
        getTaskMemberList()
        templateListFn()
    },
    { deep: true }
)
watch(
    () => checkList.value,
    (val) => {
        if (val.length > 0) {
            templateList.list.forEach(item => {
                item[`templatechecked1`] = false
                item[`templatechecked2`] = false
                item[`templatechecked3`] = false
            })
        }
    },
    { deep: true }
)
onMounted(() => {
    getTaskMemberList()
    templateListFn()
    taskListFn()
})
</script>
<style lang="less" scoped>
.dialogContent {
    width: 860px;
    .dialogModel {
        .modelTitle {
            font-size: 16px;
            line-height: 18px;
            height: 18px;
            padding-left: 10px;
            border-left: 4px solid #58be3f;
            margin-bottom: 10px;
            font-weight: 500;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            .operateIcon {
                margin-left: 10px;
                img {
                    width: 18px;
                    height: 18px;
                    margin: 0 2px;
                    cursor: pointer;
                }
            }
        }
    }
}

.operateIcon {
    display: flex;
    flex-direction: row;
    align-items: center;
}
.taskInfo {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    padding: 10px 0;
    p {
        margin-right: 60px;
        font-size: 14px;
    }
}
.templateInfo {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    .templateInfoItem {
        border: 1px solid #58be3f;
        background: #f7fcf6;
        border-radius: 8px;
        display: block;
        padding: 10px;
        width: 200px;
        margin-right: 20px;
        &.all {
            width: 100%;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            flex-wrap: wrap;
            p {
                margin-right: 20px;
            }
        }
        .templateInfoItemHeader {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            .itemTitle {
                line-height: 2;
            }
            .itemChecked {
                margin-right: 10px;
            }
        }
        .templateInfoItemContent {
            p {
                line-height: 2;
            }
        }
    }
}
.loactionResult {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    .loactionResultValue {
        margin-right: 10px;
    }
    .loactionResultValueItem {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 4px;
    }
}
.curveEquation {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
}

.el-col-content-mr {
    margin-right: 10px;
    cursor: pointer;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
}
.calculationFormula {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    margin-bottom: 12px;
    .calculationFormulaContent {
        flex: 1;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        flex-wrap: wrap;
        .calculationFormulaContentItem {
            position: relative;
            .delelteItem {
                position: absolute;
                right: 1px;
                top: -3px;
                z-index: 1000;
                background: #f56c6c;
                border-radius: 4px;
                padding: 2px 2px 0px;
            }
        }
        p {
            width: 72px;
            text-align: right;
            margin-right: 26px;
        }
    }
}
.contentStyle {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    overflow: hidden;
}
.success {
    color: #58be3f;
}
.danger {
    color: #f56c6c;
}
.warning {
    color: #e6a23c;
}
.nomarl {
    color: #666;
}
</style>